package com.k2data.k2app.service;

import com.k2data.k2app.domain.SysUser;
import com.k2data.k2app.domain.SysUserPermission;
import com.k2data.k2app.domain.vo.Customer;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.SysUserPermissionMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author clb
 */
@Log4j2
@Service
public class SysUserPermissionService {


    @Autowired
    public SysUserPermissionMapper sysUserPermissionMapper;


    @Transactional
    public int updateByUser(SysUser sysUser) throws K2ResponseException {
        if(sysUser.getId() != null){
            sysUserPermissionMapper.deleteByUserId(sysUser.getId());
        }
        //关联
        int num = 0;
        if(sysUser.getCustomers() != null){
            List<Customer> customers = sysUser.getCustomers();
            List<SysUserPermission> list = new ArrayList<>();
            customers.forEach(s->{
                SysUserPermission sysUserPermission = new SysUserPermission();
                sysUserPermission.setCustomerId(s.getId());
                sysUserPermission.setUserId(sysUser.getId());
                List<String> permissions = s.getPermission();
                permissions.forEach(a->{
                    if("editPermission".equals(a)){
                        sysUserPermission.setEditPermission("yes");
                    } else if("delPermission".equals(a)){
                        sysUserPermission.setDelPermission("yes");
                    }
                });
                list.add(sysUserPermission);
            });




            if(customers.size()>0){
                num = sysUserPermissionMapper.insertBatch(list);
            }
        }
        return num;
    }


    public List<SysUserPermission> selectByUser(Long userId){
        return sysUserPermissionMapper.selectByUserId(userId);
    }
}
